package com.example.huajia.wx.service.impl;

import cn.hutool.core.date.DateTime;
import com.example.huajia.wx.db.dao.TbOrderDao;
import com.example.huajia.wx.db.dao.TbProductDao;
import com.example.huajia.wx.service.OrderService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import static com.example.huajia.wx.common.util.RedisKey.ORDER_MINE_KEY;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private TbOrderDao orderDao;

    @Resource
    private TbProductDao productDao;

    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public int insertOrder(HashMap param) {
        int row = orderDao.insertOrder(param);
        if (row == 0){
            return row;
        }
        Integer userId = (Integer) param.get("userId");
        String key = ORDER_MINE_KEY + userId;
        redisTemplate.expire(key, 0L, TimeUnit.SECONDS);
        return row;
    }

    @Override
    public int updateStock(HashMap param) {
        int row = productDao.updateStock(param);
        return row;
    }

    @Override
    public ArrayList<HashMap> searchMyOrder(HashMap param) {
        ArrayList<HashMap> list = orderDao.searchMyOrder(param);
        Integer userId = (Integer) param.get("userId");
        //把数据存到redis中去
        String key = ORDER_MINE_KEY + userId;
        //查询完之后需要把数据写到redis里面去
        for (HashMap map : list){
            redisTemplate.opsForList().rightPush(key, map);
        }
        redisTemplate.expire(key, 30L, TimeUnit.MINUTES);
        return list;
    }
}
